package com.byq.mm.smartlib.cluster;



import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;

import com.byq.mm.smartlib.component.Rotate3dAnimation;


public class AnimationController {
	View container;
	View first;
	View second;
	boolean sd = false;
	private void applyRotation(boolean direction, float start, float end) {
		// Find the center of the container
		final float centerX = container.getWidth() / 2.0f;
		final float centerY = container.getHeight() / 2.0f;

		// Create a new 3D rotation with the supplied parameter
		// The animation listener is used to trigger the next animation
		final Rotate3dAnimation rotation = new Rotate3dAnimation(start, end,
				centerX, centerY, 310.0f, true);
		rotation.setDuration(500);
		rotation.setFillAfter(true);
		rotation.setInterpolator(new AccelerateInterpolator());
		rotation.setAnimationListener(new DisplayNextView(direction));

		container.startAnimation(rotation);
	}

	public void flap() {
		if(sd){
		applyRotation(sd, 0, 90);
		}else{
			applyRotation(sd, 180, 90);
		}
		
	}

	public AnimationController(View container, View first, View second, boolean d) {
		super();
		this.container = container;
		this.first = first;
		this.second = second;
		sd = d;
	}

	/**
	 * This class listens for the end of the first half of the animation. It
	 * then posts a new action that effectively swaps the views when the
	 * container is rotated 90 degrees and thus invisible.
	 */
	private final class DisplayNextView implements Animation.AnimationListener {
		boolean direction;

		private DisplayNextView(boolean d) {
			direction = d;
		}

		public void onAnimationStart(Animation animation) {
		}

		public void onAnimationEnd(Animation animation) {
			container.post(new SwapViews(direction));
		}

		public void onAnimationRepeat(Animation animation) {
		}
	}

	/**
	 * This class is responsible for swapping the views and start the second
	 * half of the animation.
	 */
	private final class SwapViews implements Runnable {
		boolean direction;

		public SwapViews(boolean position) {
			direction = position;
		}

		public void run() {
			final float centerX = container.getWidth() / 2.0f;
			final float centerY = container.getHeight() / 2.0f;
			Rotate3dAnimation rotation;

			if (direction) {
				first.setVisibility(View.GONE);
				second.setVisibility(View.VISIBLE);
				second.requestFocus();

				rotation = new Rotate3dAnimation(90, 180, centerX, centerY,
						310.0f, false);
			} else {
				second.setVisibility(View.GONE);
				first.setVisibility(View.VISIBLE);
				first.requestFocus();

				rotation = new Rotate3dAnimation(90, 0, centerX, centerY,
						310.0f, false);
			}

			rotation.setDuration(500);
			rotation.setFillAfter(true);
			rotation.setInterpolator(new DecelerateInterpolator());

			container.startAnimation(rotation);
		}
}
}
